package com.kitchen.api.controller;


import com.kitchen.common.utils.ImageUtils;
import com.kitchen.service.ImagesService;
import com.kitchen.common.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;


@CrossOrigin
@RestController
@RequestMapping("/image")
@Api(value = "统一图片上传接口")
public class ImageController {
    @Autowired
    ImagesService imagesService;
    @PostMapping("/addimage")
    @ApiOperation("上传图片")
    public ResultVO addimage(MultipartFile file) throws IOException {
        String file1 = ImageUtils.file(file);
        ResultVO resultVO = new ResultVO();
        int status=imagesService.addImage(file1);
        if (status>0){
            resultVO.setCode(10000);
            resultVO.setMsg("success");
            resultVO.setData(file1);
        }else {
            resultVO.setCode(10001);
            resultVO.setMsg("error");
            resultVO.setData("error");
        }
        return resultVO;
    }

    @GetMapping("/img")
    @ApiOperation("获取图片")
    @Cacheable(cacheNames = "src")
    @ApiImplicitParam(name = "src" , value = "图片路径，一般为获取到的图片路径",required = true)
    public void img(String src,HttpServletResponse response) throws IOException {
        //读取目标文件，写出给客户端
        System.out.println(src);
        IOUtils.copy(new FileInputStream("D:/kitchen/"+src), response.getOutputStream());
    }
}
